const api = require('../../utils/api.js');
import { getUserAvatarUrl, getDefaultUserAvatar } from '../../utils/persona.js';

Page({
  data: {
    avatarUrl: '',
    nickname: '',
    signature: '',
    gender: '',
    hasChanges: false,
    saving: false,
    originalData: {}
  },

  onLoad() {
    this.loadProfile();
  },

  async loadProfile() {
    try {
      const res = await api.getUserInfo();
      if (res.code === 200) {
        const data = res.data;
        this.setData({
          avatarUrl: getUserAvatarUrl(data.avatar_url),
          nickname: data.nickname || '',
          signature: data.signature || '',
          gender: data.gender || '',
          originalData: {
            avatarUrl: getUserAvatarUrl(data.avatar_url),
            nickname: data.nickname || '',
            signature: data.signature || '',
            gender: data.gender || ''
          }
        });
      } else {
        this.setData({
          avatarUrl: getDefaultUserAvatar(),
          originalData: { avatarUrl: getDefaultUserAvatar() }
        });
      }
    } catch (e) {
      this.setData({
        avatarUrl: getDefaultUserAvatar(),
        originalData: { avatarUrl: getDefaultUserAvatar() }
      });
    }
  },

  goBack() {
    if (this.data.hasChanges) {
      wx.showModal({
        title: '提示',
        content: '有未保存的修改，确定要离开吗？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      });
    } else {
      wx.navigateBack();
    }
  },

  chooseAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        if (res.tempFiles[0].size > 5 * 1024 * 1024) {
          wx.showToast({
            title: '图片不能超过5MB',
            icon: 'none'
          });
          return;
        }
        this.setData({ 
          avatarUrl: tempFilePath,
          hasChanges: true 
        });
      },
      fail: () => {
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  onNicknameInput(e) {
    const nickname = e.detail.value;
    this.setData({ 
      nickname,
      hasChanges: this.checkHasChanges(nickname, this.data.signature)
    });
  },

  onSignatureInput(e) {
    const signature = e.detail.value;
    this.setData({
      signature,
      hasChanges: this.checkHasChanges(this.data.nickname, signature)
    });
  },

  checkHasChanges(nickname = this.data.nickname, signature = this.data.signature) {
    const original = this.data.originalData;
    return nickname !== original.nickname || 
           this.data.avatarUrl !== original.avatarUrl ||
           signature !== original.signature;
  },

  async saveProfile() {
    if (this.data.saving) return;
    this.setData({ saving: true });

    try {
      wx.showLoading({ title: '保存中...', mask: true });

      if (this.data.avatarUrl !== this.data.originalData.avatarUrl) {
        const uploadRes = await api.uploadAvatar(this.data.avatarUrl);
        if (uploadRes.code !== 200) {
          throw new Error(uploadRes.msg || '头像上传失败');
        }
      }

      let updateData = {};
      if (this.data.nickname !== this.data.originalData.nickname) {
        updateData.nickname = this.data.nickname;
      }
      if (this.data.signature !== this.data.originalData.signature) {
        updateData.signature = this.data.signature;
      }
      if (Object.keys(updateData).length > 0) {
        const updateRes = await api.updateProfile(updateData);
        if (updateRes.code !== 200) {
          throw new Error(updateRes.msg || '资料更新失败');
        }
      }

      wx.hideLoading();
      wx.showToast({ title: '保存成功', icon: 'success' });

      this.setData({
        originalData: {
          avatarUrl: this.data.avatarUrl,
          nickname: this.data.nickname,
          signature: this.data.signature,
          gender: this.data.gender
        },
        hasChanges: false
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 1200);

    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none'
      });
    } finally {
      this.setData({ saving: false });
    }
  }
});